package com.dwy2002.common.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 订单号生成类
 *
 * @author 杜伟毅
 * @version 1.0
 * @since 2025/03/07
 */
public class OrderNumberGenerator {

    /**
     * 时间格式模板（精确到毫秒）
     */
    private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    /**
     * 随机数长度
     */
    private static final int RANDOM_NUMBER_LENGTH = 4;

    /**
     * 随机数格式模板
     */
    private static final String RANDOM_FORMAT = "%0" + RANDOM_NUMBER_LENGTH + "d";

    public static String generateOrderNumber() {
        // 获取当前时间戳
        String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMATTER);

        // 生成指定位数的随机数（线程安全方式）
        int randomBound = (int) Math.pow(10, RANDOM_NUMBER_LENGTH);
        int randomNumber = ThreadLocalRandom.current().nextInt(randomBound);

        // 组合时间戳和随机数
        return timestamp + String.format(RANDOM_FORMAT, randomNumber);
    }
}
